<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:include page="/WEB-INF/common/urls.jsp"/>
<html lang="zh-CN">
<head>
    <title>${applicationScope.PROJECT_NAME}-用户图书管理</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, shrink-to-fit=no">
    <link rel="icon" href="${pageContext.request.contextPath}/favicon.ico" type="image/ico">
    <link rel="stylesheet"
          href="${pageContext.request.contextPath}/lib/bootstrap-5.3.0-alpha1-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/global.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/main.css">
    <script src="${pageContext.request.contextPath}/lib/bootstrap-5.3.0-alpha1-dist/js/bootstrap.bundle.min.js"></script>
    <script src="${pageContext.request.contextPath}/lib/jquery-3.5.1.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/toast-manager.js"></script>
    <script>
        const STORAGE_KEY = 'selectedBooks'
        const CURRENT_PAGE_KEY = 'currentBookPage'
        const BOOK_MANAGEMENT_PATHS = ['/admin/books_condition', '/admin/view/book_management']
        $(() => {
            /* 分页按钮点击时将条件加入url参数 */
            $('.page-link').each((index, element) => {
                const $link = $(element)
                const originalHref = $link.attr('href')

                $link.on('click', e => {
                    e.preventDefault()

                    // 解析原始href中的URL和参数
                    const url = new URL(originalHref, window.location.origin)
                    const params = url.searchParams

                    // 获取当前页面的参数
                    const currentParams = new URLSearchParams(window.location.search)

                    // 将当前页面的参数添加到新URL中，但不覆盖链接中已有的参数
                    currentParams.forEach((value, key) => {
                        if (!params.has(key)) {
                            params.append(key, value)
                        }
                    })

                    // 设置新的搜索参数
                    url.search = params.toString()

                    // 跳转到新的URL
                    window.location.href = url.toString()
                })
            })

            // 跨页面批量删除
            const STORAGE_KEY = 'selectedBooks'
            let selectedBooks = new Set(JSON.parse(localStorage.getItem(STORAGE_KEY)) || [])
            const currentPath = window.location.pathname

            const isBookManagementPage = (path) => {
                if (!path) return false
                return BOOK_MANAGEMENT_PATHS.some(bookPath => bookPath && path.includes(bookPath))
            }

            const updateSelectedCount = () => {
                $('#selectedCount').text(selectedBooks.size);
            }

            const updateUI = () => {
                $('.delete-check').each((_, checkbox) => {
                    const $checkbox = $(checkbox);
                    const bookId = $checkbox.data('book-id');
                    if (bookId !== undefined) {
                        $checkbox.prop('checked', selectedBooks.has(bookId.toString()));
                    }
                });
                $('#batchDeleteBtn').prop('disabled', selectedBooks.size === 0);
                updateSelectedCount();
            }

            const saveState = () => {
                localStorage.setItem(STORAGE_KEY, JSON.stringify([...selectedBooks]));
            }

            const clearStateIfNeeded = () => {
                const storedPage = localStorage.getItem(CURRENT_PAGE_KEY)
                if (!isBookManagementPage(storedPage) || !isBookManagementPage(currentPath)) {
                    selectedBooks.clear()
                    localStorage.removeItem(STORAGE_KEY)
                }
                localStorage.setItem(CURRENT_PAGE_KEY, currentPath)
            }

            clearStateIfNeeded()
            updateUI()

            $('.delete-check').on('change', function () {
                const bookId = $(this).data('book-id');
                if (bookId !== undefined) {
                    if (this.checked) {
                        selectedBooks.add(bookId.toString());
                    } else {
                        selectedBooks.delete(bookId.toString());
                    }
                    saveState();
                    updateUI();
                }
            });

            $('#batchDeleteBtn').on('click', () => {
                if (selectedBooks.size > 0 && confirm("确定要删除选中的" + selectedBooks.size + "本图书吗？")) {

                    const idsString = Array.from(selectedBooks).join(',')
                    $.ajax({
                        url: '${adminUrl}/book_batch_delete',
                        method: 'GET',
                        contentType: 'application/x-www-form-urlencoded',
                        data: {ids: idsString},
                        success: (response) => {
                            selectedBooks.clear()
                            saveState()
                            location.reload()
                        },
                        error: () => {
                            alert('删除失败，请重试')
                        }
                    })
                }
            })

            const addParamsToUrl = (url, params) => {
                if (!url) return ''
                const urlObj = new URL(url, window.location.origin)
                params.forEach((value, key) => {
                    if (!urlObj.searchParams.has(key)) {
                        urlObj.searchParams.append(key, value)
                    }
                })
                return urlObj.toString()
            }

            $('.page-link').on('click', function (e) {
                e.preventDefault()
                const href = $(this).attr('href')
                if (href) {
                    const newUrl = addParamsToUrl(href, new URLSearchParams(window.location.search))
                    saveState()
                    window.location.href = newUrl
                }
            })

            $('form').on('submit', function (e) {
                e.preventDefault()
                const formData = new FormData(this)
                const params = new URLSearchParams(formData)
                const newUrl = addParamsToUrl(this.action, params)
                saveState()
                window.location.href = newUrl
            })

            // 单独删除
            $('.delete-btn').on('click', function () {
                const bookId = $(this).data('book-id');
                const $row = $(this).closest('tr');

                if (confirm("确定要删除这本图书吗？")) {
                    $.ajax({
                        url: `${adminUrl}/book_delete`,
                        method: 'get',
                        data: {bookId: bookId},
                        dataType: 'json',
                        success: (response) => {
                            const {message, isSuccess} = response;
                            showToast(message, isSuccess);

                            if (isSuccess) {
                                // 从DOM中移除该行
                                $row.remove();

                                // 无论该书是否被选中，都尝试从selectedBooks中删除
                                selectedBooks.delete(bookId.toString());
                                saveState();

                                // 更新UI
                                updateUI();
                            }
                        },
                        error: (xhr, status, error) => {
                            showToast("删除失败，请重试", false);
                            console.error("删除图书时出错:", error);
                        }
                    });
                }
            });

            const cleanupSelectedBooks = () => {
                const existingBookIds = new Set($('.delete-check').map((_, el) => $(el).data('book-id').toString()).get());
                selectedBooks = new Set([...selectedBooks].filter(id => existingBookIds.has(id)));
                saveState();
            }

            cleanupSelectedBooks();
            updateUI();

        })
    </script>
</head>

<body>
<!-- 定义一个导航栏，使用Bootstrap的navbar类，并设置其为展开、深色背景和次要背景色 -->
<header class="navbar navbar-expand-lg navbar-dark bg-body-secondary">
    <!-- 容器流体类，用于使内容在页面上居中对齐 -->
    <div class="container-fluid">
        <!-- 导航栏品牌链接，包含一个SVG图标和一个项目名称 -->
        <a class="navbar-brand navbar-logo" href="#">
            <!-- SVG图标，用于显示品牌的Logo -->
            <svg class="logo" width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
                <!-- 第一个路径元素，绘制Logo的一部分轮廓 -->
                <path d="M10,5 L30,5 L35,10 L35,35 L5,35 L5,10 L10,5" fill="none" stroke="#1E88E5" stroke-width="2"/>
                <!-- 第二个路径元素，绘制Logo的另一部分轮廓 -->
                <path d="M10,5 L10,10 L5,10" fill="none" stroke="#1E88E5" stroke-width="2"/>
                <!-- 第三个路径元素，绘制Logo中的线条 -->
                <path d="M12,15 L28,15 M12,20 L28,20 M12,25 L28,25 M12,30 L28,30" stroke="#1E88E5" stroke-width="1.5"/>
            </svg>
            <!-- 显示项目名称，使用EL表达式动态插入项目名称 -->
            <span>${applicationScope.PROJECT_NAME}</span>
        </a>
    </div>
</header>

<main class="main">
    <!-- 侧边栏 -->
    <jsp:include page="sidebar.jsp"/>
    <!-- 主体部分 -->
    <div class="main-content">
        <!-- 查询表单 -->
        <form class="mb-4" method="get" action="${adminUrl}/books_condition">
            <div class="row g-3">
                <div class="col-md-3">
                    <label for="title" class="form-label">图书标题</label>
                    <input type="text" class="form-control" id="title" name="title">
                </div>
                <div class="col-md-3">
                    <label for="author" class="form-label">作者</label>
                    <input type="text" class="form-control" id="author" name="author">
                </div>
                <div class="col-md-3">
                    <label for="isbn" class="form-label">ISBN</label>
                    <input type="text" class="form-control" id="isbn" name="isbn">
                </div>
                <div class="col-md-3">
                    <label for="categoryName" class="form-label">图书类别</label>
                    <select class="form-select" id="categoryName" name="categoryName">
                        <option value="">全部</option>

                        <c:forEach var="category" items="${categoryList}">
                            <option value="${category.categoryName}">${category.categoryName}</option>
                        </c:forEach>

                    </select>
                </div>
            </div>
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">查询</button>
                <button type="reset" class="btn btn-secondary">重置</button>
            </div>
        </form>

        <div class="d-flex mb-3 align-items-end">
            <button id="batchDeleteBtn" class="btn btn-danger">批量删除</button>
            <span class="ms-3">已选中 <span id="selectedCount">0</span> 本图书</span>
        </div>

        <!-- 订单表格 -->
        <table class="table table-bordered table-striped table-hover">
            <thead>
            <tr>
                <th>#</th>
                <th>图书ID</th>
                <th>标题</th>
                <th>作者</th>
                <th>出版社</th>
                <th>出版日期</th>
                <th>ISBN</th>
                <th>分类号</th>
                <th>类别</th>
                <th>总副本数</th>
                <th>可用副本数</th>
                <th style="width: 134px">操作</th>
            </tr>
            </thead>
            <tbody>
            <c:forEach var="item" items="${list}">
                <tr>
                    <td><input class="form-check-input delete-check" type="checkbox" data-book-id="${item.bookId}"></td>
                    <td>${item.bookId}</td>
                    <td>${item.title}</td>
                    <td>${item.author}</td>
                    <td>${item.publisher}</td>
                    <td>${item.publishDate}</td>
                    <td>${item.isbn}</td>
                    <td>${item.classificationNumber}</td>
                    <td>${item.categoryName}</td>
                    <td>${item.totalCopies}</td>
                    <td class="available-copies">${item.availableCopies}</td>
                    <td>
                        <a href="${adminUrl}/view/book_edit?id=${item.bookId}" class="edit-btn btn btn-sm btn-primary"
                           data-book-id="${item.bookId}">编辑</a>
                        <button class="delete-btn btn btn-sm btn-danger" data-book-id="${item.bookId}">删除</button>
                    </td>
                </tr>
            </c:forEach>
            </tbody>
        </table>
        <%-- 分页 --%>
        <c:set var="pageNum" value="${param.pageNum == null ? 1 : param.pageNum}"/>
        <ul class="pagination">
            <li class="page-item">
                <a class="page-link" href="${adminUrl}/books_condition?pageNum=${pageNum - 1}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            <c:forEach var="itemPageNum" begin="1" end="${pageCount}">
                <li class="page-item">
                    <a class="page-link" href="${adminUrl}/books_condition?pageNum=${itemPageNum}">
                            ${itemPageNum}
                    </a>
                </li>
            </c:forEach>
            <li class="page-item">
                <a class="page-link" href="${adminUrl}/books_condition?pageNum=${pageNum + 1}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </div>
</main>
<jsp:include page="/footer"/>
</body>
</html>